package pers.cj.pdos.controller.analysis;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.cj.pdos.controller.base.BaseController;
import pers.cj.pdos.controller.entity.ResponseData;
import pers.cj.pdos.entity.Company;
import pers.cj.pdos.entity.ProfitsReport;
import pers.cj.pdos.service.IProfitsReportService;
import pers.cj.pdos.utils.PdosUtils;
import pers.cj.pdos.utils.Utils;
import pers.cj.pdos.vo.UserVo;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/financeCount")
public class ProfitAnalysisController extends BaseController {
    @Autowired
    IProfitsReportService profitsReportService;

    @RequiresPermissions("profitAnalysis:query")
    @RequestMapping("/profitAnalysis")
    public String profitAnalysis() {
        return "analysis/profits/profitAnalysis";
    }

    @ResponseBody
    @RequestMapping("/profitAnalysis/profitsData")
    public ResponseData profitsData(String storeId,
                                        String date1,
                                        String date2) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<ProfitsReport> in_list = new ArrayList<>();
        List<ProfitsReport> out_list = new ArrayList<>();
        BigDecimal total_in = new BigDecimal(0);
        BigDecimal total_out = new BigDecimal(0);
        for(ProfitsReport report : profitsReportService.profitsData(company.getId(), Utils.genDate(date1),Utils.genDate(date2), PdosUtils.getViewOtherStoreId(userVo,storeId))) {
            if (report.getAmount() == null) {
                report.setAmount(new BigDecimal(0));
            }

            if (report.getType() == 1) {
                in_list.add(report);
                total_in = total_in.add(report.getAmount());
            } else {
                out_list.add(report);
                total_out = total_out.add(report.getAmount());
            }
        }



        List<ProfitsReport> list = new ArrayList<>();
        list.add(new ProfitsReport(0,"【收入类】",total_in));
        for (ProfitsReport report : in_list) {
            list.add(report);
        }
        list.add(new ProfitsReport(0,"【支出类】",total_out));
        for (ProfitsReport report : out_list) {
            list.add(report);
        }

        Map<String,Object> map = new HashMap<>();
        map.put("profits", total_in.subtract(total_out));
        map.put("inAmt", total_in);
        map.put("outAmt", total_out);
        map.put("list", list);

        return ResponseData.success(map);
    }


}
